package com.hitqz.robot.netty;

import cn.hutool.core.collection.CollectionUtil;
import com.hitqz.robot.api.dispatch.model.MessageDto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xupkun
 * @date 2023/7/17
 */
@Slf4j
public class ChannelCache {


    public static volatile Map<ChannelId, ChannelHandlerContext> channelHandlerContextMap =new ConcurrentHashMap<>();

    public static void add(ChannelHandlerContext ctx) {
        log.info("添加通道数据 {}---{}", ctx.channel().remoteAddress().toString(), ctx.channel().id());
        channelHandlerContextMap.put(ctx.channel().id(), ctx);
    }

    public static void remove(ChannelHandlerContext ctx) {
        channelHandlerContextMap.remove(ctx.channel().id());
    }

    public static ChannelHandlerContext findByChannelId(ChannelId channelId) {
        return channelHandlerContextMap.get(channelId);
    }

    public static void send2All(String msg){
        for (ChannelId channelId: channelHandlerContextMap.keySet()) {
            ChannelHandlerContext  ctx = channelHandlerContextMap.get(channelId);
            if(ctx != null) {
                ctx.channel().writeAndFlush(msg);
                log.debug("send data to server {}-- {}", ctx.channel().remoteAddress().toString(),  msg);
            }
        }
    }


    public static void send2All(MessageDto msg){
        if (CollectionUtil.isNotEmpty(channelHandlerContextMap)) {
            for (ChannelId channelId: channelHandlerContextMap.keySet()) {
                ChannelHandlerContext  ctx = channelHandlerContextMap.get(channelId);
                if(ctx != null) {
                    ctx.channel().writeAndFlush(msg);
                    log.debug("send data to server {}-- {}", ctx.channel().remoteAddress().toString(),
                            new String(msg.getData(), StandardCharsets.UTF_8));
                }
            }
        }
    }






}
